<template>
  <view class="dashboard">
    <tabTopBar
      :title="''"
      :isOpenRightSolt="true"
      :isOpenLeftSolt="true"
      :bgColor="'#132034'"
    >
      <template #left-arrow>
        <view class="header-left" @click="isShowNode = true">
          <text>{{ $t(nodeName) }}</text>
          <up-icon
            name="arrow-down"
            color="#fff"
            size="14"
            style="margin-left: 20rpx; padding-top: 8rpx"
          ></up-icon>
        </view>
      </template>
      <template #right-content>
        <view class="header-right" @click="goMessage">
          <up-badge :type="type" max="99" :value="isShowMessageDot"></up-badge>
          <up-icon size="20" name="/static/dashboard/bell.png"></up-icon>
        </view>
      </template>
    </tabTopBar>
    <view class="content" v-if="dataPage">
      <template v-if="dataPage.isTotalStation">
        <!-- 电站数 -->
        <sitePage :dataPage="dataPage" />
        <powerStationItem :dataPage="dataPage" />

        <template v-if="isShowEcharts">
          <!-- 图表 -->
          <echarts-electricity
            :isSetEcharts="isSetEcharts"
            :siteType="siteType"
            ref="echartsElectricitys"
          />
        </template>
      </template>
      <view
        class="site-content"
        v-if="!dataPage.isTotalStation && dataPage.totalStation < 1"
        @click="addSite"
      >
        <view class="site-content-item">
          <image src="/static/dashboard/no-site.png" mode="" />
        </view>
        <view class="add-site">
          <up-icon name="plus-circle" color="#fff" size="24"></up-icon>
          <text>
            {{ $t("dashboard.pleaseAddTheSiteFirst") }}
            <!-- 请先添加站点 -->
          </text>
        </view>
      </view>
    </view>
    <!-- 五站点 -->

    <!-- 添加站点弹框 -->
    <up-popup
      :show="isShowPoup"
      @close="close"
      closeable
      closeOnClickOverlay
      round="20"
    >
      <view class="popup">
        <view
          class="locale-list"
          :style="{ paddingTop: '100rpx', boxSizing: 'border-box' }"
        >
          <view
            class="locale-item"
            v-for="(item, index) in bindingData"
            :key="index"
          >
            <view
              class="locale-item"
              :class="bindingType == item.type ? 'locale-item-active' : ''"
              @click="onSelectBinDing(item)"
            >
              {{ item.text }}
            </view>
          </view>
        </view>
      </view>
    </up-popup>

    <!-- 添加节点点弹框 -->
    <up-popup
      :show="isShowNode"
      @close="nodeClose"
      closeOnClickOverlay
      round="20"
    >
      <view class="popup">
        <view class="header">
          <view class="title">
            {{ $t("dashboard.switchNodes") }}
            <!-- 切换节点  -->
          </view>
          <view class="selected">
            <!-- <image src="/static/login/tick.png" mode="" /> -->
            <!-- <up-button
              type="primary"
              size="mini"
              @click="handleSetNode"
              :text="$t('dashboard.areYouSure')"
            ></up-button> -->
            <!-- <text @click="handleSetNode">
              {{ $t("dashboard.areYouSure") }}
            </text> -->
          </view>
        </view>
        <view class="locale-list">
          <view
            class="locale-item"
            v-for="(item, index) in nodeData"
            :key="index"
          >
            <view
              class="locale-item"
              :class="isSelectNode == item.id ? 'locale-item-active' : ''"
              @click="onSelectNode(item)"
            >
              {{ $t(item.text) }}
            </view>
          </view>
        </view>
      </view>
    </up-popup>
    <tabBar></tabBar>
  </view>
</template>

<script>
import sitePage from "./components/sitePage.vue";
import powerStationItem from "./components/powerStationItem.vue";
import echartsElectricity from "./components/echartsElectricity.vue";
import apis from "@/apis/index.js";
import { useLocaleStore } from "@/store/locale";
import { cookie } from "@/utils/cookie.js";
import permision from "@/utils/permission";

// import { useI18n } from "vue-i18n";
// const { t } = useI18n();

// import { startScan } from "@/utils/utils";
export default {
  components: {
    sitePage,
    powerStationItem,
    echartsElectricity,
  },
  data() {
    return {
      isShowEcharts: true,
      isShowMessageDot: 0,
      isShowPoup: false,
      isShowNode: false,
      isSetEcharts: false,
      siteType: 0,
      bindingData: [
        {
          text: this.$t("dashboard.scanTheCodeToBind"),
          type: 1,
        },
        {
          text: this.$t("dashboard.manualBinding"),
          type: 2,
        },
      ],
      isSelectNode: 0,
      nodeName: "dashboard.smartChoice",
      nodeObj: {
        text: "",
        id: "",
      },
      nodeData: [
        {
          text: "dashboard.smartChoice",
          id: 0,
        },
        {
          text: "dashboard.chinaNode",
          id: "vilionChinaSqlserverDataSource",
        },
        {
          text: "dashboard.europeanNode",
          id: "vilionGlobalSqlserverDataSource",
        },
      ],

      bindingType: 1,
      dataPage: {},
    };
  },
  onPullDownRefresh() {
    this.initData();
    this.getMessage();
    this.isSetEcharts = !this.isSetEcharts;
  },
  onHide() {
    this.isShowEcharts = false;
  },
  mounted() {},
  onShow() {
    this.isShowEcharts = true;
    this.initData();
    this.getMessage();
    this.setNode();
  },
  methods: {
    async initData() {
      await this.setNode();
      await this.init();
      // 数据获取完成后停止下拉刷新动画
      uni.stopPullDownRefresh();
    },
    init() {
      let params = {
        siteType: this.siteType,
      };
      apis.getBaseData(params).then((res) => {
        if (res.code == 200) {
          this.dataPage = res.data;
          if (this.dataPage.totalStation == 0) {
            this.dataPage.isTotalStation = false;
          } else {
            this.dataPage.isTotalStation = true;
          }
        }
      });
    },
    setNode() {
      const nodeCookie = useLocaleStore();
      const { SetNodeVal, applicationLocale } = nodeCookie;
      let isSelectNode = cookie.get("isSelectNode");
      this.isSelectNode = isSelectNode ? isSelectNode : 0;
      console.log("isSelectNode", isSelectNode);
      this.nodeData.forEach((item) => {
        if (item.id == this.isSelectNode) {
          this.nodeName = item.text;
        }
      });

      // let nodeName = cookie.get("nodeName");
      // this.nodeName = nodeName ? nodeName : this.$t("dashboard.smartChoice");

      if (isSelectNode == 0) {
        this.siteType = applicationLocale == "zh-Hans" ? 0 : 1;
      } else {
        this.siteType =
          isSelectNode == "vilionChinaSqlserverDataSource" ? 0 : 1;
      }
      cookie.set("siteType", this.siteType);
      if (this.isSelectNode) {
        SetNodeVal(this.isSelectNode);
      } else if (applicationLocale == "zh-Hans") {
        console.log("中国节点");
        SetNodeVal("vilionChinaSqlserverDataSource");
      } else {
        SetNodeVal("vilionGlobalSqlserverDataSource");
        console.log("欧洲节点");
      }
    },
    nodeClose() {
      this.setNode();
      this.isShowNode = false;
    },
    handleSetNode() {
      cookie.set("isSelectNode", this.nodeObj.id);
      cookie.set("nodeName", this.nodeObj.text);
      this.initData();
      this.getMessage();
      this.isSetEcharts = !this.isSetEcharts;
      this.isShowNode = false;
      this.$nextTick(() => {
        console.log(
          "this.$refs.echartsElectricitys",
          this.$refs.echartsElectricitys
        );
        this.$refs.echartsElectricitys.isShowEarnings();
      });
    },
    onSelectNode(item) {
      this.nodeObj = {
        text: item.text,
        id: item.id,
      };
      this.isSelectNode = item.id;
      cookie.set("isSelectNode", this.nodeObj.id);
      cookie.set("nodeName", this.nodeObj.text);
      this.initData();
      this.getMessage();
      this.isSetEcharts = !this.isSetEcharts;
      this.isShowNode = false;
      this.$nextTick(() => {
        console.log(
          "this.$refs.echartsElectricitys",
          this.$refs.echartsElectricitys
        );
        this.$refs.echartsElectricitys.isShowEarnings();
      });
    },

    getMessage() {
      apis.getSystemMessageNoReadStateNumber({}).then((res) => {
        if (res.code == 200) {
          this.isShowMessageDot = res.data;
        }
      });
    },
    goMessage() {
      uni.navigateTo({
        url: "/pages/system-message/system-message",
      });
    },
    addSite() {
      this.isShowPoup = true;
    },
    close() {
      this.isShowPoup = false;
    },
    // checkScanPermission(sourceType) {
    //   return new Promise((resolve, reject) => {
    //     permision
    //       .authorize(sourceType)
    //       .then((result) => {
    //         if (!result) {
    //           uni.showModal({
    //             title: this.$t("common.permissionPrompts"),
    //             content: `${this.$t("common.pleaseGrant")}${
    //               sourceType === "album"
    //                 ? this.$t("common.photoAlbum")
    //                 : this.$t("common.camera")
    //             }${this.$t("common.permissionToUseTheFeature")}`,
    //             confirmText: this.$t("common.goToSettings"),
    //             cancelText: this.$t("common.cancel"),
    //             success: (res) => {
    //               if (res.confirm) {
    //                 permision.gotoAppPermissionSetting();
    //               }
    //             },
    //           });
    //         }
    //         resolve(result);
    //       })
    //       .catch(reject);
    //   });
    // },
    async onSelectBinDing(e) {
      console.log("e", e);
      this.bindingType = e.type;
      if (this.bindingType == 2) {
        uni.navigateTo({
          url: "/pages/dashboard/bindTheSite",
        });
      } else if (this.bindingType == 1) {
        permision.checkScanCodePermissions("camera").then((res) => {
          if (res) {
            uni.scanCode({
              hideAlbum: true,
              onlyFromCamera: true,
              success: (result) => {
                let params = {
                  emsCode: result.result,
                };
                apis.addSearchSite(params).then((res) => {
                  if (res.code == 200) {
                    uni.navigateTo({
                      url: `/pages/dashboard/scanBingDing?data=${JSON.stringify(
                        res.data
                      )}`,
                    });
                  }
                });
              },
              fail: (err) => {
                uni.showToast({
                  title: this.$t("common.scanErr"),
                  icon: "none",
                });
              },
            });
          } else {
            uni.showModal({
              title: this.$t("common.permissionPrompts"),
              content: `${this.$t("common.pleaseGrant")}${this.$t(
                "common.camera"
              )}${this.$t("common.permissionToUseTheFeature")}`,
              confirmText: this.$t("common.goToSettings"),
              cancelText: this.$t("common.cancel"),
              success: (res) => {
                if (res.confirm) {
                  uni.openAppAuthorizeSetting();
                }
              },
            });
          }
        });
      }
    },
  },
};
</script>

<style lang="scss">
.dashboard {
  width: 100%;

  .header-left {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .header-right {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .icon-with-dot {
      padding: 3rpx;
      width: 20rpx;
      height: 20rpx;
      line-height: 20rpx;
      text-align: center;
      font-size: 18rpx;
      background-color: red;
      border-radius: 50%;
    }
  }

  .content {
    margin: 24rpx auto;
    padding: 0 32rpx;

    .site-content {
      width: 686rpx;
      height: 229rpx;
      padding: 24rpx;
      box-sizing: border-box;
      margin: 30rpx auto;
      background: #132034;
      position: relative;

      .site-content-item {
        width: 100%;
        height: 100%;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .add-site {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        text {
          margin-top: 15rpx;
          font-family: Alibaba PuHuiTi 3;
          font-size: 28rpx;
          font-weight: 500;
          font-variation-settings: "opsz" auto;
          color: #ffffff;
        }
      }
    }
  }

  .popup {
    width: 100%;
    max-height: 50vh;
    overflow-y: scroll;

    .header {
      width: 100%;
      position: relative;
      text-align: center;
      padding: 30rpx 56rpx;
      box-sizing: border-box;

      .title {
        font-family: Alibaba PuHuiTi 3;
        font-size: 34rpx;
        font-weight: 500;
        font-variation-settings: "opsz" auto;
        /* 白 */
        color: #ffffff;
      }

      .selected {
        position: absolute;
        top: 30rpx;
        right: 56rpx;

        // display: flex;
        // justify-content: flex-end;
        // align-items: center;
        // background-color: #64b7f6;
        // padding: 2rpx 10rpx;
        image {
          width: 32rpx;
          height: 32rpx;
          margin-right: 10rpx;
        }

        text {
          font-family: Alibaba PuHuiTi 3;
          font-size: 28rpx;
          font-weight: 500;
          font-variation-settings: "opsz" auto;
          font-feature-settings: "kern" on;
          /* 白 */
          color: #64b7f6;
        }
      }
    }

    .locale-list {
      width: 520rpx;
      margin: 0 auto;

      .locale-item {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        background-color: #132034;
        font-size: 32rpx;
        font-weight: 500;
        text-align: center;
        color: #ffffff;
        border: 1rpx solid #1f3651;
        border-radius: 50rpx;
        margin-bottom: 30rpx;
      }

      .locale-item-active {
        background-color: $locale-background-color;
      }
    }
  }
}
</style>
